import { getUsername } from '@/utils/auth'
/*
 *username，operateTime，deviceModel,options
 */

var CbiCollect = (function () {
  var DEFAULT_CONFIG = {
    api: '',
    ssoSource:'',
    appKey:'',
  };
  var collectParams = {
    operateTime: '',
    deviceModel: '',
    ssoSource:'',
    appKey:'',
    options: {
      page: [],
      username: '',
      params: {},
    }
  };
  var utils = {
    typeDetector: function (data) {
      //类型检测
      return Object.prototype.toString.call(data)
    },
    getCookie(cookieName) {
      var strCookie = document.cookie;
      var arrCookie = strCookie.split("; ");
      for(var i = 0; i < arrCookie.length; i++){
          var arr = arrCookie[i].split("=");
          if(cookieName == arr[0]){
              return arr[1];
          }
      }
      return "";
    },
    postData: function (params) {
        //发送请求
        try {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', DEFAULT_CONFIG.api, true);
            xhr.send(params);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        try {

                        } catch (e) {
                            throw Error('你访问的页面出错了');
                        }
                    } else {
                        var error = 'Bad HTTP status: ' + xhr.status + ' ' + xhr.statusText;
                        console.log(error);
                    }
                }
            };
        } catch (e) {
            console.log(e);
        }
    }
  };

  function init(initData) {
    //初始化方法
    if (utils.typeDetector(initData) === '[object Object]') {
        if (!initData.api) {
            throw Error('error: need an Url');
        }
        for (var key in initData) {
            if (initData.hasOwnProperty(key)) {
                DEFAULT_CONFIG[key] = initData[key];
            }
        }
    } else {
        throw Error('Type error: The expectation is the object type');
    }
    collectParams['deviceModel'] = navigator.userAgent;
    collectParams['appKey'] = DEFAULT_CONFIG['appKey'];
    collectParams['ssoSource'] = DEFAULT_CONFIG['ssoSource'];
  }

  function track(options) {
    //数据采集方法
  collectParams['operateTime'] = new Date().getTime();		
      if (utils.typeDetector(options) === '[object Object]') {
          collectParams['options'] = { ...options, username: getUsername('username')}
          utils.postData(JSON.stringify(collectParams));
      } else {
          throw Error('Type error: The expectation is the object type');
  }
  // console.log(collectParams)
  }

  return {
    init:init,
    track:track
  }
})();
export default CbiCollect
